package com.example.tao.mycar.fragment;

import android.app.Activity;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.example.tao.mycar.R;
import com.example.tao.mycar.entity.PersonDataEntity;
import com.example.tao.mycar.utils.Tools;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;

import java.util.ArrayList;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link WeightLineChartFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link WeightLineChartFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class WeightLineChartFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private LineChart mLineChart;
    private RelativeLayout mView;
    private String mLabel;
    private LinearLayout mNoDataView;
    private ArrayList<PersonDataEntity> weightTimeDataArray = new ArrayList<>();
    private final int MAX_POINT = 7;

    private OnFragmentInteractionListener mListener;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment WeightLineChartFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static WeightLineChartFragment newInstance(String param1, String param2) {
        WeightLineChartFragment fragment = new WeightLineChartFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public WeightLineChartFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_weight_line_chart, container, false);
        mView = (RelativeLayout) view.findViewById(R.id.id_rl_weight_curve_chart);
        initView(mView);
        return view;
    }

    private void initView(View view) {
        mLineChart = (LineChart) view.findViewById(R.id.line_chart);
        mNoDataView = (LinearLayout) view.findViewById(R.id.no_data_view);
        int dataSize = weightTimeDataArray.size();
        if (dataSize == 0) {
            mLineChart.setVisibility(View.GONE);
            mNoDataView.setVisibility(View.VISIBLE);
        } else {
            mLineChart.setVisibility(View.VISIBLE);
            mNoDataView.setVisibility(View.GONE);
        }
        LineData mLineData = getLineData();
        showChart(mLineChart, mLineData, getResources().getColor(R.color.light_red_color));
    }

    // 设置显示的样式
    private void showChart(LineChart lineChart, LineData lineData, int color) {
        lineChart.setDrawBorders(false);  //是否在折线图上添加边框

        // no description text
        lineChart.setDescription("");// 数据描述
        // 如果没有数据的时候，会显示这个，类似listview的emtpyview
        lineChart.setNoDataTextDescription("You need to provide data for the chart.");

        // enable / disable grid background
        lineChart.setDrawGridBackground(false); // 是否显示表格颜色
        lineChart.setGridBackgroundColor(getResources().getColor(R.color.light_red_color)); // 表格的颜色，在这里是是给颜色设置一个透明度
        lineChart.getXAxis().setLabelsToSkip(0);
        lineChart.getAxisRight().setEnabled(false);
        lineChart.getAxisRight().setDrawGridLines(false);
        lineChart.getXAxis().setDrawGridLines(false);//隐藏X轴竖网格线
        lineChart.getXAxis().setEnabled(true);
        lineChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);
        lineChart.getXAxis().setTextColor(getResources().getColor(R.color.white_50_alpha));
        lineChart.getXAxis().setAxisLineColor(getResources().getColor(R.color.white_50_alpha));
        lineChart.getAxisLeft().setEnabled(false);
        lineChart.getAxisLeft().setDrawGridLines(false);
        // enable touch gestures
        lineChart.setTouchEnabled(true); // 设置是否可以触摸
        lineChart.setExtraLeftOffset(20);//添加偏移，否则日期显示不全
        lineChart.setExtraRightOffset(20);

        // enable scaling and dragging
        lineChart.setDragEnabled(true);// 是否可以拖拽
        lineChart.setScaleEnabled(false);// 是否可以缩放

        // if disabled, scaling can be done on x- and y-axis separately
        lineChart.setPinchZoom(false);//

        lineChart.setBackgroundColor(color);// 设置背景

        // add data
        lineChart.setData(lineData); // 设置数据

        // get the legend (only possible after setting data)
        Legend mLegend = lineChart.getLegend(); // 设置比例图标示，就是那个一组y的value的

        // modify the legend ...
        mLegend.setEnabled(false);//隐藏table
//         mLegend.setPosition(Legend.LegendPosition.PIECHART_CENTER);
        mLegend.setForm(Legend.LegendForm.LINE);// 样式
        mLegend.setFormSize(2f);// 字体
        mLegend.setTextColor(Color.BLUE);// 颜色
//      mLegend.setTypeface(mTf);// 字体
//        lineChart.animateX(2500); // 立即执行的动画,x轴
    }

    /**
     * 生成一个数据
     *
     * @return
     */
    private LineData getLineData() {
        ArrayList<String> xValues = new ArrayList<>();
        ArrayList<Entry> yValues = new ArrayList<>();

        if (weightTimeDataArray.size() >= 0 && weightTimeDataArray.size() <= MAX_POINT) {
            for (int i = 0; i <= MAX_POINT - 1; i++) {
                // x轴显示的数据，这里默认使用数字下标显示
                if (i < weightTimeDataArray.size()) {
                    PersonDataEntity personDataEntity = weightTimeDataArray.get(i);
                    String month =  Tools.getMonthFromDatePicker(personDataEntity.getTime()).replaceAll("0", "");
                    String time = month + "-" + Tools.getDayFromDatePicker(personDataEntity.getTime());
                    xValues.add(time);
                    float weight = Float.parseFloat(personDataEntity.getWeight());
                    yValues.add(new BarEntry(weight, i));
                } else {
                    xValues.add("");
                    yValues.add(new BarEntry(null, i));
                }
            }
        } else if (weightTimeDataArray.size() > MAX_POINT) {
            int size = weightTimeDataArray.size() - MAX_POINT;

            for (int i = size; i <= weightTimeDataArray.size() - 1; i++) {
                // x轴显示的数据，这里默认使用数字下标显示
                PersonDataEntity personDataEntity = weightTimeDataArray.get(i);
                String month = Tools.getMonthFromDatePicker(personDataEntity.getTime()).replaceAll("0", "");
                String time = month + "-" + Tools.getDayFromDatePicker(personDataEntity.getTime());
                xValues.add(time);
                float weight = Float.parseFloat(personDataEntity.getWeight());
                yValues.add(new BarEntry(weight, i - size));
            }
        }

        // create a dataset and give it a type
        // y轴的数据集合
        LineDataSet lineDataSet = new LineDataSet(yValues, mLabel /*显示在比例图上*/);
        lineDataSet.setFillAlpha(110);

        //用y轴的集合来设置参数
        lineDataSet.setLineWidth(1.75f); // 线宽
        lineDataSet.setCircleSize(3f);// 显示的圆形大小
        lineDataSet.setColor(Color.WHITE);// 显示颜色
        lineDataSet.setCircleColor(Color.WHITE);// 圆形的颜色
        lineDataSet.setValueTextColor(getResources().getColor(R.color.white_50_alpha));
//        lineDataSet.setHighLightColor(getResources().getColor(R.color.red_color)); // 高亮的线的颜色
        lineDataSet.setDrawHighlightIndicators(false);//禁掉，点击高亮线
        lineDataSet.setDrawCircles(true);
        lineDataSet.setDrawCubic(true);
        lineDataSet.setCubicIntensity(0.0f);
        lineDataSet.setDrawFilled(true);
        lineDataSet.setFillColor(getResources().getColor(R.color.light_red_color));

        ArrayList<LineDataSet> lineDataSets = new ArrayList<LineDataSet>();
        lineDataSets.add(lineDataSet); // add the datasets

        // create a data object with the datasets
        LineData lineData = new LineData(xValues, lineDataSets);

        return lineData;
    }

    public void setTimeWeightDataArray(ArrayList<PersonDataEntity> arrayList) {
        weightTimeDataArray = arrayList;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            //mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        //public void onFragmentInteraction(Uri uri);
    }

}
